import { parseTime } from './common'

import { lodashUniqBy, lodashMap } from '@/utils/lodashUtil'

import { completeFilePath } from '@/api/common.js'

import * as shortUUID from 'short-uuid'
import Cookies from 'js-cookie'

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == '') return ''
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) {
      s++
    } else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

export const creatteUrlParams = param

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * 合并数组
 * @param uuid 区分 对象的唯一标记
 * */
export function mergesArray(mainList, subList, uuid = 'id') {
  var newMainList = [].concat(mainList)
  for (let i = 0; i < subList.length; i++) {
    var subItem = subList[i]
    var hasIndexInMain = mainList.findIndex(mainItem => mainItem[uuid] == subItem[uuid])
    if (hasIndexInMain < 0/*没有在主列表上，加入*/) {
      newMainList.push(subItem)
    }
  }
  return newMainList
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
// export function debounce(func, wait, immediate) {
//   let timeout, args, context, timestamp, result;
//
//   const later = function () {
//     // 据上一次触发时间间隔
//     const last = +new Date() - timestamp
//
//     // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
//     if (last < wait && last > 0) {
//       timeout = setTimeout(later, wait - last)
//     } else {
//       timeout = null
//       // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
//       if (!immediate) {
//         result = func.apply(context, args)
//         if (!timeout) context = args = null
//       }
//     }
//   }
//
//   return function (...args) {
//     context = this
//     timestamp = +new Date()
//     const callNow = immediate && !timeout
//     // 如果延时不存在，重新设定延时
//     if (!timeout) timeout = setTimeout(later, wait)
//     if (callNow) {
//       result = func.apply(context, args)
//       context = args = null
//       return result
//     }
//
//     return Promise.resolve();
//   }
// }

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
import { cloneDeep } from 'lodash-es'

export const deepClone = cloneDeep

export const debounce = (func, wait = 50) => {
  // 缓存一个定时器id
  let timer = 0
  // 这里返回的函数是每次用户实际调用的防抖函数
  // 如果已经设定过定时器了就清空上一次的定时器
  // 开始一个新的定时器，延迟执行用户传入的方法
  return function(...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, wait)
  }
}

/**
 * 创建并返回一个像节流阀一样的函数，当重复调用函数的时候，最多每隔delay毫秒调用一次该函数
 * @param fn 执行函数
 * @param delay 时间间隔
 * @returns {Function}
 */

export function throttle(fn, delay) {
  var timer = null
  var timeStamp = new Date()
  return function() {
    var context = this  //获取函数所在作用域this
    var args = arguments  //取得传入参数
    if (new Date() - timeStamp > delay) {
      timeStamp = new Date()
      timer = setTimeout(function() {
        fn.apply(context, args)
      }, delay)
    }

  }
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/-[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}

export function isInteger(str) {
  return /^-?\d+$/.test(str)
}


export function uniqBy(array, key) {
  return lodashUniqBy(array, key)
}

export function map2array(map) {
  return Object.keys(map).map(key => {
    return map[key]
  })
}

export function setPriceForForm(price) {
  if (!price) return 0
  return price * 100
}

export function setPriceForShow(price) {
  if (!price) return 0
  return price / 100
}

export function createA(href, target) {
  var a = document.createElement('a')
  a.setAttribute('href', href)
  a.setAttribute('target', target || '_blank')
  a.setAttribute('id', 'startTelMedicine')
  // 防止反复添加
  if (document.getElementById('startTelMedicine')) {
    document.body.removeChild(document.getElementById('startTelMedicine'))
  }
  document.body.appendChild(a)
  a.click()
}

/** 判断是不是空 */
export function isNil(str) {
  if (str == undefined) {
    return true
  }
  if (str == null) {
    return true
  }
  if (str == '') {
    return true
  }

  if (str == 0) {
    return false
  }

  if (str == '0') {
    return false
  }
  return true
}

/** 判断是不是空 */
export function isUndefinedOrNull(str) {
  if (str == undefined) {
    return true
  }
  if (str == null) {
    return true
  }
  return false
}

/** 过期方法弹出框*/
export function messageBox401() {
  /*return MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
      confirmButtonText: '重新登录',
      cancelButtonText: '取消',
      type: 'warning'
      // showClose: false,
      // closeOnClickModal: false,
      // showCancelButton: false
    }
  )*/
  return triggerMessageBox401()
}

export function alert401() {
  /*if(/!*不在 钉钉*!/dd.env.platform == "notInDingTalk"){
    }else{
    return  Promise.reject()
  }*/
  let SINGLE_ALERT = Cookies.get('SINGLE_403_ALERT')
  if (!SINGLE_ALERT) {
    Cookies.set('SINGLE_403_ALERT', 1, { expires: 1 / 24 / 60 })
  } else {
    return Promise.reject('弹出框不会弹出框第二次')
  }

  return

}

/** uuid*/
export function createUUID() {
// Quick start with flickrBase58 format
  var _shortUUID_default = shortUUID.default
  var shortUUID_default = _shortUUID_default && _shortUUID_default() || shortUUID
  return shortUUID_default.generate() // 73WakrfVbNJBaAmhQtEeDv
}

function isNumeric(value) {
  if (typeof value === 'number') {
    return !isNaN(value);
  }
  if (typeof value === 'string') {
    return !isNaN(value) && !isNaN(parseFloat(value));
  }
  return false;
}

//是否是整数
function isIntegerZeng(str) {
  return /^[1-9]\d*$/.test(str);
}


export function safeParseInt(str) {
  try {
    if(/*不是整数 直接‘’*/!isIntegerZeng(str)){
      return ''
    }
     if(isNumeric(str)){
       return parseInt(str)
     }
     return ''
  } catch (e) {
    console.error(e)
    return ''
  }
}

export function safeParseIntStrict(str) {
  try {
    if(/*不是整数 直接‘’*/!isIntegerZeng(str)){
      return 0
    }
    if(isNumeric(str)){
      return parseInt(str)
    }
    return 0
  } catch (e) {
    console.error(e)
    return 0
  }
}




export function safeParseString(str) {
  if (!str) {
    return ''
  }
  return str + ''
}

export function safeParseFloat(str) {
  if (!str) {
    return ''
  }
  return parseFloat(str)
}

export function safeParseFloatNull(str) {
  if (isNaN(str)) {
    return undefined
  }
  if (str === undefined) {
    return undefined
  }
  if (str === null) {
    return undefined
  }
  if (str === '') {
    return undefined
  }
  return parseFloat(str)
}

function isObject(data) {
  return typeof data === 'object' && data !== null && !Array.isArray(data);
}
export function safeParseJson(str) {
  try {
    if (str == '') return ''
    if(isObject(str)){
    return str;
    }
    return JSON.parse(str)
  } catch (e) {
    console.error(e)
    return undefined
  }

}

export function removeSessionStorage(str) {
  if (str/*删除指定某些key*/) {
    var len = localStorage.length
    for (let i = 0; i < len; i++) {
      var key = localStorage.key(i)
      console.log('removeSessionStorage key', key, key.indexOf(str) >= 0)
      if (key.indexOf(str) >= 0) {
        key && localStorage.setItem(key, '')
      }
    }
    return Promise.resolve()
  } else {
    localStorage.clear()
    return Promise.resolve()
  }
}

export function clearZero(obj, ignoreList = []) {
  if (!obj) return obj
  lodashMap(obj, (value, key) => {
    if (ignoreList.includes(key)) {
    } else {
      if (value == 0) {
        obj[key] = undefined
      }
    }

  })
  return obj

}

export function createArray(len, factoryItem) {
  var array = []
  for (let i = 0; i < len; i++) {
    if (factoryItem) {
      array.push(factoryItem())
    } else {
      array.push(i)
    }

  }
  return array
}

/**
 * 图片路径补充http
 * */
// export function completeNetPath(str) {
//   if (!str) return '';
//   if (str.indexOf('http') >= 0) {
//     return str;
//   }
//
//   if (str && str[0] === '/') {
//     str = str.substr(1, str.length);
//   }
//   return `${process.env.VUE_APP_BASE_API}/erp/static/${str}`;
// }
export const completeNetPath = completeFilePath

export const LoadashMap = lodashMap

export function dateFormatYYYYMMDD(value, defaultvalue = '',format='YYYY-MM-DD') {
  if (!value) return defaultvalue||''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return defaultvalue || ''
  }

  return moment(value).format(format)
}

export function dateFormatDD(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  return moment(value).format('DD')
}

export function dateFormatYYYYMM(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  var format = 'YYYY-MM'

  return moment(value).format(format)
}

export function dateFormatYYYYMMDDHH(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  var format = 'YYYY-MM-DD:HH'

  return moment(value).format(format)
}

export function dateFormatMMDD(value, defaultvalue, dateformatstr = 'MM-DD') {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return defaultvalue || ''
  }
  var format = dateformatstr || 'MM-DD'

  return moment(value).format(format)
}

export function dateFormatMMDDHHmm(value, _format = 'MM-DD HH:mm', defaultstr) {
  if (!value) return defaultstr || ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return defaultstr || ''
  }

  var format = _format || 'MM-DD HH:mm'

  return moment(value).format(format)
}

export function dateFormatHHmmss(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  return moment(value).format('HH:mm:ss')
}

export function dateFormatmmss(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  return moment(value).format('mm:ss')
}

export function dateFormatHHmm(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  return moment(value).format('HH:mm')
}

export function dateFormatYYYYMMDDHHmmss(value, defaultstr = '') {
  if (!value) return defaultstr||''
  value = value.toString()
  if (value && value.indexOf('1970-01') >= 0) {
    return defaultstr||''
  }
  var format = 'YYYY-MM-DD HH:mm:ss'
  return moment(value).format(format)
}
export function dateFormatYYYY(value,defaultstr='') {
  if (!value) return defaultstr||'';
  value = value.toString()
  if (value && value.indexOf('1970-01') >= 0) {
    return defaultstr||''
  }
  var format = 'YYYY'
  return moment(value).format(format)
}

export function dateFormateRestTime(_time) {
  if (!_time) return ''
  const now = moment() // 获取当前时间
  const endOfDay = moment(_time).endOf('day') // 设置当天的 23:59:59
  const duration = moment.duration(endOfDay.diff(now)) // 计算剩余时间的 Duration 对象
  // 获取剩余时间的小时、分钟和秒钟
  const day = duration.days()
  const hours = duration.hours()
  const minutes = duration.minutes()
  const seconds = duration.seconds()
  // console.log(hours + ':' + minutes + ':' + seconds); // 输出剩余时间
  var timestr = ''
  if (day) {
    timestr += day + '天'
  }
  if (hours) {
    timestr += hours + '时'
  }
  if (minutes) {
    timestr += minutes + '分'
  }

  return timestr
}

/*获取本月最后一天*/
export function laterDateMonth(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  const lastDayOfMonth = moment(value).endOf('month')
  var lastTime = lastDayOfMonth.endOf('s')

  var format = 'YYYY-MM-DD HH:mm:ss'

  return moment(lastTime).format(format)
}

export function startDateMonth(value) {
  if (!value) return ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return ''
  }
  const lastDayOfMonth = moment(value).startOf('month')
  var lastTime = lastDayOfMonth.startOf('s')

  var format = 'YYYY-MM-DD HH:mm:ss'

  return moment(lastTime).format(format)
}

export function dateFormatYYYYMMDDHHmm(value, defaultstr) {
  if (!value) return defaultstr || ''
  value = value.toString()
  if (value && value.indexOf('1970-01-01') >= 0) {
    return defaultstr || ''
  }
  var format = 'YYYY-MM-DD HH:mm'

  return moment(value).format(format)
}

export function isIOS() {
  var userAgent = navigator.userAgent
  var _isiOS = userAgent.includes('iPhone') || userAgent.includes('iPad')
  return _isiOS
}

export function nowWithFormat(format = 'YYYY-MM-DD HH:mm:ss') {
  return moment().format(format)
}

export function dateformat(value, format = 'YYYY-MM-DD HH:mm:ss') {
  return moment(value).format(format)
}

export function nowAfter3day(format = 'YYYY-MM-DD HH:mm:ss') {

  return moment().add(3, 'd').format(format)
}

export function nowAfter1day(format = 'YYYY-MM-DD HH:mm:ss') {

  return moment().add(1, 'd').format(format)
}

export function toDayWithFormat() {
  var format = 'YYYY-MM-DD'

  return moment().format(format)
}

/**
 * 复制value到剪贴板*/
export function copy2bang(value) {
  // for ie
  if (window.clipboardData) {
    window.clipboardData.clearData()
    window.clipboardData.setData('text', value)
  }
// for modern browser
  else if (document.execCommand) {
    var element = document.createElement('pre')
    element.textContent = value
    document.body.appendChild(element)
    if (document.selection) {
      var range = document.body.createTextRange()
      range.moveToElementText(element)
      range.select()
    } else if (window.getSelection) {
      var range = document.createRange()
      range.selectNode(element)
      window.getSelection().removeAllRanges()
      window.getSelection().addRange(range)
    }
    document.execCommand('copy')
    element.remove ? element.remove() : element.removeNode(true)
  }
}

//特点
export function scroll2Div(selectorStr) {
  setTimeout(() => {
    $('html, body').animate({
      scrollTop: $(selectorStr) && $(selectorStr).offset() && $(selectorStr).offset().top
    }, { duration: 500, easing: 'swing' })
  }, 100)

}

export function scroll2error() {
  scroll2Div('.el-form-item__error')
}

export function parseStr(str) {
  if (!str) {
    return ''
  }
  return `${str}`
}

export function getUrlParam(parameterName, currentUrl = location.href) {
  var rs = new RegExp('(^|[&,?])' + parameterName + '=([^\&]*)(\&|$)', 'gi')
    .exec(currentUrl), tmp
  if (tmp = rs) return tmp[2]
  return null
}

/**
 *去掉px
 */
export function toNumberStyle(str) {
  if (!str) return str
  var index = str.indexOf('px')
  if (index >= 0) {
    return str.substr(0, index)
  }
  return str
}

export function erpParstInt(str) {
  if (!str) return 0
  return parseInt(str)
}

export function erpParstFloat(str) {

  if (!str) return 0
  return parseFloat(str)
}

export function toReal(num = 0) {
  if (isNaN(num)) return 0
  if (!num) return num
  return Decimal(num || 0).div(100).toNumber()
}

export function toReal1000(num = 0) {
  if (isNaN(num)) return 0
  if (!num) return num
  return Decimal(num || 0).div(1000).toNumber()
}

export function toSubmit(num) {
  if (!num) return num
  return Decimal(num || 0).mul(100).toNumber()
}

export function toSubmitPlus(num) {
  if (!num) return num
  return (num * 100).toFixed(0)
}

/***
 * @DESC 根据list的面辅料生成下一个的abc
 * @expample 面料A 面料B
 * @param type
 *
 * [{"label":"面料","value":"1"},{"label":"辅料","value":"2"},{"label":"里料","value":"3"}]
 */

//字母列表
export const AlphabeticList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

export function gerenrateABC(list, type) {
  if (!type) return undefined
  if (!list) return undefined
  if (list && list.length <= 0) return undefined
  var list2 = list.filter(item => item.materialType == type)
  var now_materialSerial_list = list2.map(_item => _item['materialSerial'])
  var fitlerList = AlphabeticList.filter(_str => {
    return !(now_materialSerial_list.findIndex(_str2 => _str2 === _str) >= 0)
  })
  return fitlerList && fitlerList[0] || 'A'
}

function firstCaseUp(str) {
  var newStr = str.slice(0, 1).toUpperCase() + str.slice(1)
  return newStr
}

export function mutationsUtils(initState) {
  var keys = Object.keys(initState)
  var funs = {}
  for (let i = 0; i < keys.length; i++) {
    funs[`set${firstCaseUp(keys[i])}`] = function(state, payload) {
      state[`${keys[i]}`] = payload
    }
  }
  return funs
}

export function mapperStateutils(initStateKeys, prefix = ''/*前缀*/) {
  var funs = {}
  for (let i = 0; i < initStateKeys.length; i++) {
    funs[`${prefix}${initStateKeys[i]}`] = (state) => {
      return state[`${initStateKeys[i]}`]
    }
  }
  return funs
}

export function stateUtilForPina(initStateKeys, state, refState) {
  var funs = {}
  for (let i = 0; i < initStateKeys.length; i++) {
    if (typeof state[initStateKeys[i]] != 'object') {
      funs[`${initStateKeys[i]}`] = state[initStateKeys[i]]
    } else {
      funs[`${initStateKeys[i]}`] = refState[initStateKeys[i]]
    }
  }
  return funs
}

export function getAllKeys(initActions) {
  var allActionKeys = Object.keys(initActions)
  return allActionKeys
}

export function getActionUtils(store, actionKeys) {
  var _a = {}
  for (let i = 0; i < actionKeys.length; i++) {
    _a[actionKeys[i]] = store[actionKeys[i]]
  }
  return _a
}

function xinxinLengt(len) {
  var str = ''
  for (let i = 0; i < len; i++) {
    str += '*'
  }
  return str
}

/** 敏感*/
export function sensitiveStr(str) {
  if (str && str.length <= 2) {
    return str
  }
  /* for (var i = 2; i < str.length - 2; i++) {
     str[i] = '*';
   }*/
  if (str && str.length == 3) {
    var first = str.substr(0, 1)
    var last = str.substr(str.length - 1, 1)
    return first + `${xinxinLengt(1)}` + last
    return str
  }

  var first = str.substr(0, 2)
  var last = str.substr(str.length - 2, 2)
  return first + `${xinxinLengt(str.length - 4)}` + last
}

/**
 * @description: promise<boolean>
 * @params
 * @return
 */
export function comfirmPromise(str) {
  return window._vm.$confirm(str, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(res => {
    return true
  }).catch(e => {
    return false
  })
}

/**
 * @description:  0 return false 只有是null undefinde nan 返回true
 *    0 返回false
 * @params
 * @return boolean
 */
export function isnullfornumber(str) {
  if (str == 0) {
    return false
  }
 /* if (str == DEFAULT_NULL) {
    return true
  }*/
  return !str
}

export function isemptyfornumber(str) {
  if (str === 0) {
    return false
  }
  return !str
}

//今天最后一刻
export function endOfTimeByDay(str) {
  if (!str) return ''
  return moment(str).endOf('day').format('YYYY-MM-DD HH:mm:ss')
}

//策略模式 匹配
export function matchTopic(str = '', topicstr = '') {
  return RegExp(topicstr).test(str)
}

// import * as hrmUserApi from '@/api/manage/hrm/user.js'
// import { DEFAULT_NULL } from '@/views/components/erpInputNumber/bizUtils'

// 部门获取用户
export async function ajaxUserListByDepartId(departId) {
  // var resuklt = await hrmUserApi.getList({ departId })
  var resuklt =  {}
  return resuklt && resuklt.data || []
}

//判断放在ipad pro设备里全为false
export function isPad() {
  var u = navigator.userAgent
  return u.indexOf('iPad') > -1 //是否iPad
  // ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
}

export function sleep(time = 1000) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}

export function createWatermark(str) {
  var appDom = document.querySelector('#dialogRoot')
  var canvasDom = document.createElement('canvas')
  canvasDom.width = 100
  canvasDom.height = 100
  canvasDom.style.display = 'none'
  appDom.appendChild(canvasDom)

  const ctx = canvasDom.getContext('2d')
  let text = str
  ctx.font = '14px Verdana'
  ctx.fillStyle = 'rgba(192,196,204,0.3)'
  ctx.rotate(20 * Math.PI / 180)
  ctx.fillText(text, 20, 22)

  setTimeout(() => {
    canvasDom && canvasDom.remove()
  }, 1000)
  return canvasDom.toDataURL('image/png')

}

export function toFixedInt(_num) {
  return (_num / 100).toFixed(2)
}
export function toFixed100(_num) {
  return (_num / 100).toFixed(2)
}

export function adapterhttp(httpurl) {
  var index1 = location.href?.indexOf('https')
  var index2 = httpurl?.indexOf('https')
  console.log("=>(index.js:1229) index1", index1);
  console.log("=>(index.js:1232) index2", index2);
  if (index1 >= 0) {
    if (index2 < 0) {
      httpurl = httpurl?.replace('http', 'https')
    }
  }
  return httpurl
}
export function fixHttpUrls(text) {
  // 使用正则表达式匹配 `http:/` 后面紧跟非斜杠字符的URL
  const regex = /(http:\/)([^/])/g;

  // 使用 replace 方法替换匹配到的字符串，在 `http:/` 后面加上一个斜杠
  const fixedText = text.replace(regex, '$1/$2');

  return fixedText;
}

export function numberToChinese(money) {
  var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖') //汉字的数字
  var cnIntRadice = new Array('', '拾', '佰', '仟') //基本单位
  var cnIntUnits = new Array('', '万', '亿', '兆') //对应整数部分扩展单位
  var cnDecUnits = new Array('角', '分', '毫', '厘') //对应小数部分单位
  var cnInteger = '整' //整数金额时后面跟的字符
  var cnIntLast = '元' //整型完以后的单位
  var maxNum = 999999999999999.9999 //最大处理的数字
  var IntegerNum //金额整数部分
  var DecimalNum //金额小数部分
  var ChineseStr = '' //输出的中文金额字符串
  var parts //分离金额后用的数组，预定义
  if (money == '') {
    return ''
  }
  money = parseFloat(money)
  if (money >= maxNum) {
    alert('超出最大处理数字')
    return ''
  }
  if (money == 0) {
    ChineseStr = cnNums[0] + cnIntLast + cnInteger
    return ChineseStr
  }
  money = money.toString() //转换为字符串
  if (money.indexOf('.') == -1) {
    IntegerNum = money
    DecimalNum = ''
  } else {
    parts = money.split('.')
    IntegerNum = parts[0]
    DecimalNum = parts[1].substr(0, 4)
  }
  if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
    var zeroCount = 0
    var IntLen = IntegerNum.length
    for (var i = 0; i < IntLen; i++) {
      var n = IntegerNum.substr(i, 1)
      var p = IntLen - i - 1
      var q = p / 4
      var m = p % 4
      if (n == '0') {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          ChineseStr += cnNums[0]
        }
        zeroCount = 0 //归零
        ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
      }
      if (m == 0 && zeroCount < 4) {
        ChineseStr += cnIntUnits[q]
      }
    }
    ChineseStr += cnIntLast
    //整型部分处理完毕
  }
  if (DecimalNum != '') { //小数部分
    var decLen = DecimalNum.length
    for (var i = 0; i < decLen; i++) {
      var n = DecimalNum.substr(i, 1)
      if (n != '0') {
        ChineseStr += cnNums[Number(n)] + cnDecUnits[i]
      }
    }
  }
  if (ChineseStr == '') {
    ChineseStr += cnNums[0] + cnIntLast + cnInteger
  } else if (DecimalNum == '') {
    ChineseStr += cnInteger
  }
  return ChineseStr
}

export async function setTimePromise(_time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, _time)
  })
}

export function appendUrl(url, key, value) {
  var qindex = url?.indexOf('?')
  console.log('=>[qindex]', qindex)
  if (qindex >= 0) {
    url = url + `&${key}=${value || ''}`
    console.log('=>[url]', url)
  } else {
    url = url + `?1=1&${key}=${value || ''}`
    console.log('=>[url=]', url)
  }
  return url
}

export function numberToChinesePure(num) {
  const units = ["", "十", "百", "千", "万", "亿"];
  const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];

  if (num === 0) {
    return "零";
  }

  const numStr = num.toString();
  const len = numStr.length;
  let chinese = "";

  for (let i = 0; i < len; i++) {
    const digit = parseInt(numStr[i]);
    const unitIndex = len - 1 - i;

    if (digit !== 0) {
      chinese += digits[digit] + units[unitIndex];
    } else {
      // Handle consecutive zeros
      if (chinese.length > 0 && chinese[chinese.length - 1] !== "零" && unitIndex % 4 !== 0) { // Only add "零" if the previous character isn't "零" and it's not a "万" or "亿" place
        chinese += "零";
      }
    }
  }

  // Remove trailing zeros
  while (chinese.endsWith("零")) {
    chinese = chinese.slice(0, -1);
  }

  // Special case: if the number starts with "一十", change it to "十" (e.g., "一十二" to "十二")
  if (chinese.startsWith("一十")) {
    chinese = chinese.slice(1);
  }

  return chinese;
}

/*

export function sleep(options) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, options || 1000)

  })
}
*/



